﻿'Description:定时业务类
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer:Wangjh 
'create Date:20230807
'Rewriter:
'Rewrite Date:

Imports DatabaseAccess.DBUtility
Imports BusinessRule.DTO
Imports System.Text
Imports External.APICalling

Public Class ScheduledTaskBusiness

    ''' <summary>
    ''' 获取定时任务数据
    ''' </summary>
    ''' <param name="para"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetScheduledTaskData(ByVal para As Dictionary(Of String, String)) As uMESProcessResult
        Dim strSql = <string>SELECT ST.TASKTYPE,ST.TASKNAME,ST.TASKDESC,ST.STATUS,ST.CYCLETIME,TO_CHAR(SL.TASKEXESTARTTIME,'YYYY-MM-DD HH24:MI:SS') LASTEXCUTIME,
                        DECODE(SL.TASKEXESTARTTIME,NULL,TO_CHAR(ST.TASKSTARTTIME+ST.CYCLETIME,'YYYY-MM-DD HH24:MI:SS'),TO_CHAR(SL.TASKEXESTARTTIME+ST.CYCLETIME,'YYYY-MM-DD HH24:MI:SS'))
                        NEXTEXCUTIME2,TO_CHAR(st.NEXTEXCUTIME,'YYYY-MM-DD HH24:MI:SS') NEXTEXCUTIME,
                        TO_CHAR(ST.CREATEDATE,'YYYY-MM-DD HH24:MI:SS') CREATEDATE,TO_CHAR(ST.LASTCHANGEDATE,'YYYY-MM-DD HH24:MI:SS') LASTCHANGEDATE,
                        E.FULLNAME CREATENAME,E2.FULLNAME LASTCHANGENAME,ST.SCHEDULEDTASKID,TO_CHAR(ST.TASKSTARTTIME,'YYYY-MM-DD HH24:MI:SS') TASKSTARTTIME,
                        TO_CHAR(ST.TASKENDTIME,'YYYY-MM-DD HH24:MI:SS') TASKENDTIME
                        FROM SCHEDULEDTASK ST
                        LEFT JOIN SCHEDULEDTASKLOGS SL ON SL.SCHEDULEDTASKID=ST.SCHEDULEDTASKID AND SL.ISLATEST=1
                        LEFT JOIN EMPLOYEE E ON E.EMPLOYEEID=ST.CREATEEMPLOYEEID
                        LEFT JOIN EMPLOYEE E2 ON E2.EMPLOYEEID=ST.LASTCHANGEEMPLOYEEID
                        WHERE ST.ISUSE=0 </string>.Value

        If para.ContainsKey("FactoryID") Then
            If Not String.IsNullOrWhiteSpace("FactoryID") Then
                strSql += String.Format(" AND ST.FactoryID='{0}' ", para("FactoryID"))
            End If
        End If

        Dim paraPage As New uMESPagingDataDTO
        paraPage.CurrentPageIndex = Convert.ToInt32(para("CurrentPageIndex"))
        paraPage.PageSize = Convert.ToInt32(para("PageSize").ToString)
        paraPage.strSQL = strSql

        strSql += " ORDER BY ST.CREATEDATE "
        Dim result As uMESProcessResult = DatabaseHelper.RunProcedureForPage(paraPage)

        Return result
    End Function

    ''' <summary>
    ''' 保存定时任务
    ''' </summary>
    ''' <param name="para"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function SaveScheduledTask(ByVal para As Dictionary(Of String, String), ByVal attrDt As DataTable) As uMESProcessResult
        Dim insertStrSql = <string>insert into ScheduledTask (ScheduledTaskID,TaskName,FactoryID,TaskStartTime,TaskEndTime,TaskDesc,CycleTime,
CreateEmployeeId,LastChangeEmployeeId,CreateDate,LastChangeDate,Status,IsUse,TaskType,NEXTEXCUTIME) values ('{0}','{1}','{2}',to_date('{3}','yyyy-mm-dd hh24:mi:ss'),to_date('{4}','yyyy-mm-dd hh24:mi:ss'),'{5}',{6},'{7}',
'{8}',sysdate,sysdate,1,0,{9},to_date('{3}','yyyy-mm-dd hh24:mi:ss')+{6})</string>.Value

        Dim updateSql = <string>update ScheduledTask st set st.taskname='{0}',st.taskdesc='{1}',st.taskstarttime=to_date('{2}','yyyy-mm-dd hh24:mi:ss')
,st.taskendtime=to_date('{3}','yyyy-mm-dd hh24:mi:ss'),st.cycletime={4} ,st.lastchangeemployeeid='{5}',st.lastchangedate=sysdate,st.nextexcutime=to_date('{7}','yyyy-mm-dd hh24:mi:ss') where st.scheduledtaskid='{6}'</string>.Value

        Dim strSql = ""
        Dim sqlList As New ArrayList
        If String.IsNullOrWhiteSpace(para("ScheduledTaskId")) Then
            para("ScheduledTaskId") = Guid.NewGuid.ToString()
            strSql = String.Format(insertStrSql, para("ScheduledTaskId"), para("TaskName"), para("FactoryID"), para("TaskStartTime"), para("TaskEndTime"),
                                    para("TaskDesc"), para("Cycletime"), para("EmployeeID"), para("EmployeeID"), para("TaskType"))
        Else
            '处理下次执行时间 add:wangjh 20240827
            Dim lastestLog = DatabaseHelper.GetSingle(String.Format("select to_char(sl.TASKEXESTARTTIME,'yyyy-mm-dd hh24:mi:ss') taskexeendtime from scheduledtasklogs sl where sl.scheduledtaskid='{0}' and sl.islatest=1 and rownum=1", para("ScheduledTaskId")))
            If lastestLog Is Nothing Then
                strSql = String.Format(updateSql, para("TaskName"), para("TaskDesc"), para("TaskStartTime"), para("TaskEndTime"),
                                         para("Cycletime"), para("EmployeeID"), para("ScheduledTaskId"), Date.Parse(para("TaskStartTime")).AddDays(para("Cycletime")).ToString("yyyy-MM-dd HH:mm:ss"))

            Else
                strSql = String.Format(updateSql, para("TaskName"), para("TaskDesc"), para("TaskStartTime"), para("TaskEndTime"),
                                         para("Cycletime"), para("EmployeeID"), para("ScheduledTaskId"), Date.Parse(lastestLog).AddDays(para("Cycletime")).ToString("yyyy-MM-dd HH:mm:ss"))

            End If
        End If
        sqlList.Add(strSql)
        '处理动态属性
        For Each attrRow As DataRow In attrDt.Rows
            sqlList.Add(String.Format("DELETE  SCHEDULEDTASKATTR WHERE SCHEDULEDTASKID='{0}' AND ATTRIBUTENAME='{1}'", para("ScheduledTaskId"), attrRow("ATTRIBUTENAME").ToString()))
            sqlList.Add(String.Format(<STRING> INSERT INTO SCHEDULEDTASKATTR (SCHEDULEDTASKATTRID,SCHEDULEDTASKID,ATTRIBUTENAME,ATTRIBUTEVALUE,IsUse) VALUES(SYS_GUID(),'{0}','{1}','{2}','{3}')</STRING>.Value,
                                      para("ScheduledTaskId"), attrRow("ATTRIBUTENAME").ToString(), attrRow("ATTRIBUTEVALUE").ToString(), attrRow("IsUse").ToString()))
        Next

        DatabaseHelper.ExecuteSqlTran(sqlList)

        Dim re = New uMESProcessResult()
        re.Result = True
        Return re
    End Function

    ''' <summary>
    ''' 获取定时任务日志
    ''' </summary>
    ''' <param name="id"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetScheduledTaskLog(ByVal id As String) As DataTable
        Dim strSql = <string>select sl.ExecuteType,sl.status,to_char(sl.TaskExeStartTime,'yyyy-mm-dd hh24:mi:ss') TaskExeStartTime,
to_char(sl.TaskExeEndTime,'yyyy-mm-dd hh24:mi:ss') TaskExeEndTime,SL.LOGMESSAGE   from ScheduledTaskLogs sl
where sl.scheduledtaskid='{0}'
order by sl.createdate desc</string>.Value

        Return DatabaseHelper.Query_ReturnDatTable(String.Format(strSql, id))
    End Function

    ''' <summary>
    ''' 手动开始或停止定时任务
    ''' </summary>
    ''' <param name="para"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ManualScheduledTask(ByVal para As Dictionary(Of String, String)) As uMESProcessResult
        Dim type = para("Manualtype")
        Dim sqlList As New ArrayList
        If type = "1" Then '开始任务
            sqlList.Add(String.Format("update ScheduledTask set Status=2 where ScheduledTaskid='{0}'", para("ScheduledTaskId")))
            sqlList.Add(String.Format("update ScheduledTaskLogs set Islatest=0 where  ScheduledTaskid='{0}' and Islatest=1 ", para("ScheduledTaskId")))
            sqlList.Add(String.Format(<string>insert into ScheduledTaskLogs sl (sl.scheduledtasklogsid,sl.scheduledtaskid,sl.status,sl.islatest,sl.ManualOperEmp,sl.executetype,
sl.createdate,sl.taskexestarttime,sl.logmessage) values (sys_guid(),'{0}','2',1,'{1}',2,sysdate,sysdate,'{2}')</string>.Value, para("ScheduledTaskId"), para("ManualOperEmp"), "手动开始"))

            DatabaseHelper.ExecuteSqlListTran(sqlList)

        End If

        If type = "2" Then '停止任务
            sqlList.Add(String.Format("update ScheduledTask set Status=1 where ScheduledTaskid='{0}'", para("ScheduledTaskId")))
            sqlList.Add(String.Format(<string>update ScheduledTaskLogs sl set sl.status=4,sl.logmessage=sl.logmessage||'{0}',taskexeendtime=sysdate where sl.scheduledtaskid='{1}'
and sl.islatest=1</string>.Value, " 已手动停止", para("ScheduledTaskId")))
            DatabaseHelper.ExecuteSqlListTran(sqlList)
        End If

        Dim re = New uMESProcessResult()
        re.Result = True
        Return re
    End Function

    ''' <summary>
    ''' 根据属性获取定时任务
    ''' </summary>
    ''' <param name="attrName"></param>
    ''' <param name="attrValue"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetScheduledTaskByAttr(ByVal attrName As String, ByVal attrValue As String) As DataTable
        Dim strSql = <string>select st.taskname,st.status from ScheduledTask st
left join ScheduledTaskAttr sa on sa.scheduledtaskid=st.scheduledtaskid and sa.isuse=0
where sa.attributename=st.taskTYPE||'{0}' and st.isuse=0 and sa.attributevalue='{1}'</string>.Value
        Return DatabaseHelper.Query_ReturnDatTable(String.Format(strSql, attrName, attrValue))
    End Function

End Class
